<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Group;
use App\Models\Category;
use App\Models\Product;
use Brick\Math\RoundingMode;
use App\Services\Cache\ProductCache;
use Illuminate\Support\Facades\Cache;
use App\Http\Controllers\Api\V1\Resources\ProductResource;
use App\Http\Controllers\Api\V1\Resources\ProductListResource;
use App\Services\OpenGroup\OpenGroupRequest;
use App\Services\OpenGroup\OpenGroup;
use App\Services\OpenGroup\JoinGroupRequest;
use App\Services\MakeProductOrder\MakeProductOrder;
use App\Http\Controllers\Api\V1\Resources\GroupResource;
use App\Http\Controllers\Api\V1\Resources\OrderResource;
use App\Http\Controllers\Api\V1\Resources\GroupCardsResource;

class GroupsController extends Controller
{
	public function products()
	{

		$category  = Category::find(request('cid'));
		
		$products = app(ProductCache::class)->groupProducts($category);

		return ProductListResource::collection($products);

		
	}

	public function open()
	{
		$lock = Cache::lock('open_group', 15);

		try {

			if (! $lock->get()) fail('高峰拥挤，请再试');

			$request = app(OpenGroupRequest::class);
		

			$group = app(OpenGroup::class, [
			    'user' => $request->user(),
			    'product_id' => $request->product_id
		    ])->make();
			//dd(123);
            return new GroupResource($group);

		} finally {
			$lock->release();
		}
	}

	public function join()
	{
		$lock = Cache::lock('join_group', 15);

		try {

			if (! $lock->get()) fail('高峰拥挤，请再试');
			
			$request = app(JoinGroupRequest::class);
		
			$order = app(MakeProductOrder::class, [
			    'user' => $request->user(),
			    'address' => $request->getAddress(),
			    'items' => $request->items()
		    ])->make();

           return new OrderResource($order);

		} finally {
			$lock->release();
		}
	}
	

	public function myList()
	{

		$user = request()->user();

		$groups = $user->groups()->orderByDesc('id')->paginate();
		

		return GroupResource::collection($groups);
	}

	public function index()
	{
		$productId = request('product_id');
		if($productId){

			$groups = Group::query()->noFinished()->where('product_id',$productId)->orderBy('id')->paginate();
		}else{

			$groups = Group::query()->noFinished()->orderBy('id')->paginate();
		}
		
		return GroupResource::collection($groups);

	}

	public function show($id)
	{
		
		$group = Group::find($id);
		
		
		return new GroupResource($group);

	}

	public function cards()
	{

		$user = request()->user();

		$cards = $user->groupCards()->canUsed()->orderByDesc('id')->paginate();
		

		return GroupCardsResource::collection($cards);
	}
}
